<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="数据集" prop="typeId" v-if="!typeId">
        <el-select
          v-model="queryParams.typeId"
          placeholder="请选择分类"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="item in typeOptions"
            :key="item.id"
            :label="item.typeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="文档标题" prop="documentTitle">
        <el-input
          v-model="queryParams.documentTitle"
          placeholder="请输入文档标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文档类型" prop="documentType">
        <el-select v-model="queryParams.documentType" placeholder="请选择文档类型" clearable>
          <el-option
            v-for="dict in dict.type.document_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="文件类型" prop="fileType">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.fileType"-->
      <!--          placeholder="请输入文件类型"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="分段类型" prop="segmentType">-->
      <!--        <el-select v-model="queryParams.segmentType" placeholder="请选择分段类型" clearable>-->
      <!--          <el-option-->
      <!--            v-for="dict in dict.type.segment_type"-->
      <!--            :key="dict.value"-->
      <!--            :label="dict.label"-->
      <!--            :value="dict.value"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="用户Id" prop="userId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.userId"-->
      <!--          placeholder="请输入用户Id"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['business:document:add']"-->
<!--        >新增-->
<!--        </el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:document:edit']"
        >查看
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:document:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="documentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="文档ID" align="center" prop="id"/>
      <el-table-column label="数据集Id" align="center" prop="typeId"/>
      <el-table-column label="数据集名称" align="center" prop="typeName"/>
      <el-table-column label="文档标题" align="center" prop="documentTitle" show-overflow-tooltip />
      <el-table-column label="文档内容" align="center" show-overflow-tooltip prop="documentContent"/>
      <el-table-column label="文档类型" align="center" prop="documentType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.document_type" :value="scope.row.documentType"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="文件类型" align="center" prop="fileType"/>-->
      <!--      <el-table-column label="文档大小" align="center" prop="fileSize" />-->
      <!--      <el-table-column label="文件路径" align="center" prop="fileUrl"  show-overflow-tooltip  />-->
      <!--      <el-table-column label="分段字符数量" align="center" prop="characterLength"/>-->
      <!--      <el-table-column label="分段字符" align="center" prop="character"/>-->
      <!--      <el-table-column label="分段数量" align="center" prop="segmentCount"/>-->
      <!--      <el-table-column label="分段类型" align="center" prop="segmentType">-->
      <!--        <template slot-scope="scope">-->
      <!--          <dict-tag :options="dict.type.segment_type" :value="scope.row.segmentType"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="文档状态" align="center" prop="status"/>-->
      <el-table-column label="用户昵称" align="center" prop="nickName"/>
      <el-table-column label="时间" align="center" prop="createTime" width="180"/>
      <!--      <el-table-column label="备注" align="center" prop="remark"/>-->
      <el-table-column label="操作" width="200" fixed="right" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:document:edit']"
          >查看
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="viewSegment(scope.row)"
            v-hasPermi="['business:document:edit']"
          >查看分段信息
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            v-if="scope.row.documentType == '1'   &&   scope.row.fileUrl  "
            @click="downloadFile(scope.row)"
          >下载
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:document:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改知识库文档对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="数据集" prop="typeId">
          <el-select
            v-model="form.typeId"
            placeholder="请选择分类"
            :disabled="typeId"
            @change="setZskId"
            clearable
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.id"
              :label="item.typeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文档标题" prop="documentTitle" v-if="title!='添加知识库文档'">
          <el-input v-model="form.documentTitle" placeholder="请输入文档标题"/>
        </el-form-item>
        <el-form-item label="文档内容" v-if="title!='添加知识库文档'">

          <editor
            v-model="form.documentContent"
            :min-height="192"
          />

          <!--          <el-input v-model="form.documentContent" :rows="10" type="textarea" placeholder="请输入文档标题"/>-->
        </el-form-item>
        <el-form-item label="文档类型" prop="documentType">
          <el-select v-model="form.documentType" placeholder="请选择文档类型">
            <el-option
              v-for="dict in dict.type.document_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="文件类型" prop="fileType" v-if="title!='添加知识库文档' && form.documentType !='3'">-->
<!--          <el-input v-model="form.fileType" placeholder="请输入文件类型"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="文档大小" prop="fileSize" v-if="title!='添加知识库文档' && form.documentType !='3'">-->
<!--          <el-input v-model="form.fileSize" placeholder="请输入文档大小"/>-->
<!--        </el-form-item>-->
        <el-form-item label="网站路径" v-if="form.documentType=='3' " prop="url">
          <el-input v-model="form.url" placeholder="请输入网站路径"/>
        </el-form-item>
        <el-form-item label="文件路径" prop="fileUrl" v-if="form.documentType !='3'">
          <FileUploadDocument v-if="openupload"
                              v-model="form.fileUrl"
                              :zskId="zskId"
                              :documentId="ssuuid"
                              :file-type="['pdf','doc','docx','txt','png','jpg','jpeg','mp4']"
                              :file-size="50" :limit="1"/>
        </el-form-item>
        <!--        <el-form-item label="分段类型" prop="segmentType">-->
        <!--          <el-select v-model="form.segmentType" placeholder="请选择分段类型">-->
        <!--            <el-option-->
        <!--              v-for="dict in dict.type.segment_type"-->
        <!--              :key="dict.value"-->
        <!--              :label="dict.label"-->
        <!--              :value="dict.value"-->
        <!--            ></el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->

        <!--        <el-form-item label="分段字符数量" prop="characterLength">-->
        <!--          <el-input v-model="form.characterLength" placeholder="请输入分段字符数量"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="分段字符" prop="character">-->
        <!--          <el-input v-model="form.character" placeholder="请输入分段字符"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="分段数量" prop="segmentCount">-->
        <!--          <el-input v-model="form.segmentCount" placeholder="请输入分段数量"/>-->
        <!--        </el-form-item>-->
<!--        <el-form-item label="备注" prop="remark">-->
<!--          <editor-->
<!--            v-model="form.remark"-->
<!--            :min-height="192"-->
<!--          />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
<!--        <el-button type="primary" v-if="title !='查看知识库文档'" @click="submitForm">确 定</el-button>-->
        <el-button @click="cancel">取 消</el-button>
        <!--        <el-button icon="el-icon-close" @click="handleClose">关 闭</el-button>-->
      </div>
    </el-dialog>

    <div slot="footer" class="dialog-footer" v-if="false">
      <el-button @click="handleClose">关闭</el-button>
    </div>

    <!-- 查看分段信息对话框 -->
    <el-dialog :title="documentName+'---分段信息'" :visible.sync="segmentOpen" width="1200px" append-to-body>
      <Segment v-if="segmentOpen" :documentId="currentDocumentId"/>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDocument,
  getDocument,
  delDocument,
  addDocument,
  updateDocument,
  addToSegment
} from "@/api/business/document";
import {alllistType} from "@/api/business/type";
import Segment from "@/components/Segment/index.vue";

export default {
  name: "Document",
  dicts: ['document_type', 'segment_type'],
  components: {
    Segment
  },
  props: {
    typeId: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    return {
      openupload: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 知识库文档表格数据
      documentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型选项列表
      typeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        typeId: this.typeId,
        documentTitle: null,
        documentContent: null,
        documentType: null,
        fileType: null,
        fileSize: null,
        fileUrl: null,
        characterLength: null,
        character: null,
        segmentCount: null,
        segmentType: null,
        status: null,
        userId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        typeId: [
          {required: true, message: "分类ID不能为空", trigger: "blur"}
        ],
        documentType: [
          {required: true, message: "文档类型不能为空", trigger: "change"}
        ],
        url: [
          {required: true, message: "网站路径不能为空", trigger: "blur"}
        ],
        fileUrl: [
          {required: true, message: "文件路径不能为空", trigger: "blur"}
        ],

      },
      // 查看分段信息对话框
      segmentOpen: false,
      documentName: "",
      // 当前查看分段的文档ID
      currentDocumentId: null,
      ssuuid: "",
      zskId: "",
    };
  },
  watch: {
    typeId: {
      handler(newVal) {
        this.queryParams.typeId = newVal;
        this.getList();
      },
      immediate: true
    }
  },
  created() {
    if (this.typeId !== null) {
      this.queryParams.typeId = this.typeId;
    }
    this.getList();
    this.getAllTypes();
    this.zskId = this.typeId
  },
  methods: {
    generateUUID() {
      if (typeof crypto !== 'undefined' && crypto.randomUUID) {
        return crypto.randomUUID();
      } else {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
          var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
          return v.toString(16);
        });
      }
    },
    /** 获取所有类型选项 */
    getAllTypes() {
      alllistType().then(response => {
        this.typeOptions = response.data;
      });
    },
    /** 查询知识库文档列表 */
    getList() {
      this.loading = true;
      listDocument(this.queryParams).then(response => {
        this.documentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    setZskId() {
      this.zskId = this.form.typeId;
      this.ssuuid = this.generateUUID();
      this.openupload = true;
    },
    // // 关闭按钮操作
    // handleClose() {
    //   this.$emit('close');
    // },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        typeId: null,
        documentTitle: null,
        documentContent: null,
        documentType: null,
        fileType: null,
        fileSize: null,
        fileUrl: null,
        characterLength: null,
        character: null,
        segmentCount: null,
        segmentType: null,
        status: null,
        delFlag: null,
        userId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.ssuuid = ""; // 重置 UUID
      this.reset();
      this.openupload = false; // 重置上传组件
      if (this.typeId !== null) {
        this.form.typeId = this.typeId;
      }
      // 每次新增时重新生成UUID
      this.ssuuid = this.generateUUID();
      this.open = true;
      this.title = "添加知识库文档";

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDocument(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.openupload=true;
        this.title = "查看知识库文档";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDocument(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.id = this.ssuuid;
            addDocument(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除知识库文档编号为"' + ids + '"的数据项？').then(function () {
        return delDocument(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/document/export', {
        ...this.queryParams
      }, `document_${new Date().getTime()}.xlsx`)
    },

    /** 分段按钮操作 */
    addToSegment(row) {
      this.$modal.confirm('是否确认将文档"' + row.documentTitle + '"添加到分段？').then(function () {
        return addToSegment(row);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("分段成功");
      }).catch(() => {
      });
    },

    /** 查看分段信息 */
    viewSegment(row) {
      this.currentDocumentId = row.id;
      this.documentName = row.documentTitle;
      this.segmentOpen = true;
    },
    downloadFile(row) {
      // 下载文件
      this.$download.resourceOss(row.fileUrl)
    },
    /** 关闭分段信息弹窗 */
    closeSegment() {
      this.segmentOpen = false;
      this.currentDocumentId = null;
    }
  }
};
</script>
